package tresp.utils.team;

import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Logger;

import robocode.MessageEvent;
import tresp.bthreads.BThread;
import tresp.bthreads.BThreadType;
import tresp.coordinator.BThreadVoteType;
import tresp.coordinator.ICoordinator;
import tresp.utils.BThreadVote;
import tresp.utils.logging.MyLogger;


/**
 * <b>TeamMateMessageListener</b>
 * 
 * 
 * @author <font color="blue">Maxim Kirilov</font>
 *
 */
public class TeamMateMessageListener extends BThread {

    
    private static Logger logger = MyLogger.getLogger( TeamMateMessageListener.class );
    
    private AtomicReference<MessageEvent> lastMessageEvent;
    
    public TeamMateMessageListener(ICoordinator<BThreadVote> coordinator) {
	super(coordinator);
	logger.info("TeamMateMessageListener B-Thread created successfully");
	this.weight = 50D;
	lastMessageEvent = new AtomicReference<MessageEvent>();
    }

    @Override
    public void vote() {
	
	MessageEvent messageEvent = lastMessageEvent.getAndSet( null );
	if ( messageEvent != null ){
	    TeamMateMessage teamMateMessage = (TeamMateMessage)messageEvent.getMessage();
	    switch( teamMateMessage.getCommand() ){
	    case HOLD_FIRE:
		coordinator.vote( createBThreadVote(BThreadType.FIRE, weight, 0D), BThreadVoteType.BLOCK);
		break;
	    }
	}

    }

    
    @Override
    public void onMessageReceived(MessageEvent messageEvent){
	super.onMessageReceived( messageEvent );
	logger.info("Message received from: "+messageEvent.getSender() );
	lastMessageEvent.set( messageEvent );
	
    }
    
    
    
    @Override
    public String getName() {
	return "TeamMateMessageListener";
    }

}
